<template>
  <view class="post-container">
    <!-- 搜索区域 -->
    <view class="search-box">
      <view class="search-form">
        <view class="search-item">
          <text class="label">岗位名称</text>
          <input v-model="queryParams.postName" type="text" placeholder="请输入岗位名称" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text class="label">岗位编码</text>
          <input v-model="queryParams.postCode" type="text" placeholder="请输入岗位编码" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text class="label">状态</text>
          <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
            <view class="picker-box">
              <text :class="{ 'placeholder': !queryParams.status }">
                {{ statusOptions[statusIndex].label }}
              </text>
              <uni-icons type="bottom" size="12" color="#909399"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      <view class="btn-group">
        <view class="btn search-btn" @tap="handleQuery">
          <uni-icons type="search" size="14" color="#fff"></uni-icons>
          <text>搜索</text>
        </view>
        <view class="btn reset-btn" @tap="resetQuery">
          <uni-icons type="refresh" size="14" color="#606266"></uni-icons>
          <text>重置</text>
        </view>
        <view class="btn add-btn" @tap="handleAdd">
          <uni-icons type="plusempty" size="14" color="#fff"></uni-icons>
          <text>新增</text>
        </view>
      </view>
    </view>

    <!-- 岗位列表 -->
    <view class="post-list" v-if="postList.length > 0">
      <view v-for="(item, index) in postList" :key="index" class="post-item" @click="handleViewDetail(item)">
        <view class="post-info">
          <view class="name-row">
            <text class="post-name">{{ item.postName }}</text>
            <text class="post-code">({{ item.postCode }})</text>
            <view :class="['status-tag', item.status === '0' ? 'status-normal' : 'status-disabled']">
              {{ item.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="detail-info" v-if="item.remark">
            <text class="remark">{{ item.remark }}</text>
          </view>
          <view class="time-info">
            <text class="create-time">创建时间：{{ item.createTime }}</text>
            <text class="update-time" v-if="item.updateTime">更新时间：{{ item.updateTime }}</text>
          </view>
        </view>
        <view class="action-group">
          <view class="action-btn edit" @tap.stop="handleEdit(item)">
            <uni-icons type="compose" size="14" color="#409eff"></uni-icons>
            <text>编辑</text>
          </view>
          <view class="action-btn delete" @tap.stop="handleDelete(item)">
            <uni-icons type="trash" size="14" color="#f56c6c"></uni-icons>
            <text>删除</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus" :icon-size="16" :content-text="contentText" />
    </view>

    <!-- 空数据提示 -->
    <view v-else class="empty-box">
      <uni-icons type="info" size="50" color="#999"></uni-icons>
      <text class="empty-text">暂无岗位数据</text>
    </view>
  </view>
</template>

<script>
import { listPost, delPost, updatePost } from '@/api/system/post'

export default {
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postName: undefined,
        postCode: undefined,
        status: undefined
      },
      postList: [],
      loading: false,
      hasMore: true,
      total: 0,
      loadMoreStatus: 'more',
      contentText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      },
      statusOptions: [
        { label: '全部', value: '' },
        { label: '正常', value: '0' },
        { label: '停用', value: '1' }
      ],
      statusIndex: 0
    }
  },
  onLoad() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList(type = 'more') {
      if (this.loading) return
      this.loading = true

      try {
        const res = await listPost(this.queryParams)
        if (res.code === 200) {
          const { rows, total } = res

          if (type === 'refresh' || this.queryParams.pageNum === 1) {
            this.postList = rows
          } else {
            this.postList = [...this.postList, ...rows]
          }

          this.total = total
          this.hasMore = this.postList.length < total
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
        }
      } catch (error) {
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: '获取岗位列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (type === 'refresh') {
          uni.stopPullDownRefresh()
        }
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.postList = []
      this.hasMore = true
      this.loadMoreStatus = 'more'
      this.getList('refresh')
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        postName: undefined,
        postCode: undefined,
        status: undefined
      }
      this.statusIndex = 0
      this.handleQuery()
    },

    // 状态选择改变（搜索条件）
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.queryParams.status = this.statusOptions[this.statusIndex].value
      this.handleQuery()
    },

    // 新增岗位
    handleAdd() {
      uni.navigateTo({
        url: '/pages/system/post/form'
      })
    },

    // 编辑岗位
    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/system/post/form?postId=${item.postId}`
      })
    },

    // 查看详情
    handleViewDetail(item) {
      uni.navigateTo({
        url: `/pages/system/post/form?postId=${item.postId}&type=view`
      })
    },

    // 删除岗位
    handleDelete(item) {
      uni.showModal({
        title: '提示',
        content: `确定要删除岗位"${item.postName}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await delPost(item.postId)
              if (res.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.handleQuery()
              }
            } catch (error) {
            }
          }
        }
      })
    },

    // 修改状态切换的处理方法
    async handleSwitchChange(e, row) {
      const status = e.detail.value ? "0" : "1"
      try {
        const res = await updatePost({
          postId: row.postId,
          status: status
        })
        if (res.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
          this.getList('refresh')
        }
      } catch (error) {
        uni.showToast({
          title: '修改失败',
          icon: 'none'
        })
      }
    }
  },
  // 下刷新
  onPullDownRefresh() {
    this.queryParams.pageNum = 1
    this.getList('refresh')
  },
  // 上拉加载
  onReachBottom() {
    if (this.hasMore) {
      this.queryParams.pageNum++
      this.getList()
    }
  }
}
</script>

<style lang="scss">
.post-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20rpx;

  .post-list {
    .post-item {
      background-color: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .post-info {
        .name-row {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;

          .post-name {
            font-size: 32rpx;
            font-weight: 600;
            color: #2c3e50;
          }

          .post-code {
            font-size: 28rpx;
            color: #909399;
            margin: 0 16rpx;
          }

          .status-tag {
            padding: 4rpx 16rpx;
            border-radius: 6rpx;
            font-size: 24rpx;

            &.status-normal {
              background-color: #f0f9eb;
              color: #67c23a;
            }

            &.status-disabled {
              background-color: #f4f4f5;
              color: #909399;
            }
          }
        }

        .detail-info {
          margin-bottom: 16rpx;

          .remark {
            font-size: 28rpx;
            color: #606266;
          }
        }

        .time-info {
          display: flex;
          flex-direction: column;
          gap: 8rpx;
          font-size: 24rpx;
          color: #909399;
        }
      }

      .action-group {
        margin-top: 24rpx;
        padding-top: 24rpx;
        border-top: 2rpx solid #f0f2f5;
        display: flex;
        justify-content: flex-end;
        gap: 24rpx;

        .action-btn {
          display: flex;
          align-items: center;
          padding: 12rpx 24rpx;
          border-radius: 8rpx;
          font-size: 26rpx;
          transition: all 0.3s;

          &:active {
            opacity: 0.8;
            transform: scale(0.98);
          }

          text {
            margin-left: 8rpx;
          }

          &.edit {
            background-color: #ecf5ff;
            color: #409eff;
          }

          &.delete {
            background-color: #fef0f0;
            color: #f56c6c;
          }
        }
      }
    }
  }

  .empty-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .empty-text {
      font-size: 28rpx;
      color: #909399;
      margin-top: 20rpx;
    }
  }
}
</style>